/*
 * $Id: SendMail.java,v 1.4 2009/08/21 14:49:16 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.common.util.mail;

/**
 * @author 212042764
 *
 */
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.common.util.ServiceLocator;

/**
 * @author 212042764 - Navdeep Mahajan
 * 
 */
public class SendMail {
	// Mail constants
	private static ServiceLocator serviceLocator = null;
	private static String mailSessionJNDIName = null;
	private static final String CONTENT_FORMAT = "text/plain";
	// private static final String UPM_MAIL_JNDI_NAME =
	// "insite2.mail.session.upm";
	private static final String SMTP_HOST_NAME_PROP = "mail.smtp.host";
	private static final String COMMA_DELIMITOR = ",";

	/**
	 * Sends mail to the specified address with the specified content All the
	 * properties for sending mail are read from the database properties table
	 * 
	 * @param strContent
	 * @throws MessagingException
	 */
	public static void createNotify(String strContent, String strToAddresses,
			String strSubject, String hostName, String strFrom,
			String strCCAddresses, String strBCCAddresses)
			throws MessagingException {
		String methodName = "createNotify";
		Session session = null;
		if (ASCUtil.isNullOrEmptyObject(serviceLocator)) {
			ASCLogger
					.warn(
							SendMail.class,
							methodName,
							"You are using default mail session which can cause issues in production, use weblogic mail session instead");
			Properties props = new Properties();
			props.put(SMTP_HOST_NAME_PROP, hostName);
			session = Session.getDefaultInstance(props, null);
		} else {
			session = (Session) serviceLocator.getService(mailSessionJNDIName);
		}

		// build the message
		MimeMessage msg = new MimeMessage(session);
		msg.setContent(strContent, CONTENT_FORMAT);
		msg.setSubject(strSubject);
		msg.setFrom(new InternetAddress(strFrom));
		Address[] arrTo = null;
		if (!isNullOrEmpty(strToAddresses)) {
			arrTo = getAddress(strToAddresses);
			msg.addRecipients(Message.RecipientType.TO, arrTo);
		}
		Address[] Cc = null;
		if (!isNullOrEmpty(strCCAddresses)) {
			Cc = getAddress(strCCAddresses);
			if (Cc.length > 0) {
				msg.addRecipients(Message.RecipientType.CC, Cc);
			}
		}
		Address[] Bcc = null;
		if (!isNullOrEmpty(strBCCAddresses)) {
			Bcc = getAddress(strBCCAddresses);
			if (Bcc.length > 0) {
				msg.addRecipients(Message.RecipientType.BCC, Bcc);
			}
		}
		msg.setSentDate(new GregorianCalendar().getTime());
		Transport.send(msg);
	}

	public static void createNotify(MailInfo mailInfo)
			throws MessagingException {

		Properties props = new Properties();
		props.put(SMTP_HOST_NAME_PROP, mailInfo.getServerHostName());
		Session session = Session.getDefaultInstance(props, null);

		// build the message
		MimeMessage msg = new MimeMessage(session);
		msg.setSubject(mailInfo.getEmailSubject());
		msg.setFrom(new InternetAddress(mailInfo.getSenderAddress()));
		msg.addRecipients(Message.RecipientType.TO, mailInfo
				.getRecipientAddresses());
		if (mailInfo.anyCcRecipients()) {
			msg.addRecipients(Message.RecipientType.CC, mailInfo
					.getCcRecipientAddresses());
		}
		if (mailInfo.anyBccRecipients()) {
			msg.addRecipients(Message.RecipientType.BCC, mailInfo
					.getBccRecipientAddresses());
		}

		MimeMultipart multiPart = new MimeMultipart();
		MimeBodyPart emailBodyPart = new MimeBodyPart();
		emailBodyPart.setText(mailInfo.getEmailBody());
		multiPart.addBodyPart(emailBodyPart);

		if (mailInfo.anyAttachment()) {
			Set<Attachment> attachments = mailInfo.getAttachements();
			Iterator<Attachment> iter = attachments.iterator();
			while (iter.hasNext()) {
				Attachment attachment = iter.next();
				MimeBodyPart attachmentPart = new MimeBodyPart();
				attachmentPart.setDataHandler(new DataHandler(attachment
						.getAttachmentDS()));
				attachmentPart.setFileName(attachment.getAttachmentName());
				multiPart.addBodyPart(attachmentPart);
			}
		}
		msg.setContent(multiPart);
		msg.setSentDate(new GregorianCalendar().getTime());
		Transport.send(msg);
	}

	/**
	 * Creates an Address object from the list of addresses ( '|' seperated)
	 * specified
	 * 
	 * @param strAddress
	 *            - Pipe seperated list of email addresses
	 * @return - an array of Address object to which the email needs to be sent
	 * @throws AddressException
	 */
	private static Address[] getAddress(String strAddress)
			throws AddressException {
		if (isNullOrEmpty(strAddress)) {
			return null;
		}
		final String[] toAddresses = strAddress.split(COMMA_DELIMITOR);
		Address[] arrHolder = new Address[toAddresses.length];
		for (int iCount = 0; iCount < toAddresses.length; iCount++) {
			arrHolder[iCount] = new InternetAddress(toAddresses[iCount]);
		}
		return arrHolder;
	}

	private static boolean isNullOrEmpty(String string) {
		if (string == null || "".equals(string.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * @param serviceLocator
	 *            the serviceLocator to set
	 */
	public void setServiceLocator(ServiceLocator serviceLocator) {
		SendMail.serviceLocator = serviceLocator;
	}

	/**
	 * @param mailSessionJNDIName
	 *            the mailSessionJNDIName to set
	 */
	public void setMailSessionJNDIName(String mailSessionJNDIName) {
		SendMail.mailSessionJNDIName = mailSessionJNDIName;
	}
}
